package com.fzkj.queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @DESCRIPTION 阻塞队列demo
 */
public class BlockingQueueDemo {

    public static void main(String[] args) throws InterruptedException {
//        exception_blockingQueue();
//        trueFalseBlockingQueue();
        BlockQueue();
    }

    private static void BlockQueue() throws InterruptedException {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3);
        queue.put(1);
        queue.put(1);
        queue.put(1);
        // 超过容量会阻塞，一直等到有位置
//        queue.put(1);

        queue.take();
        queue.take();
        queue.take();
        // 超过会阻塞，等待获取
        //        queue.take();
    }

    // 在超过初始化容量时返回 false
    private static void trueFalseBlockingQueue() throws InterruptedException {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3);
        queue.offer(1);
        queue.offer(1);
        System.out.println(queue.offer(1));
        // 超过容量时添加失败,返回false
        System.out.println(queue.offer(1));

        System.out.println(queue.peek()); // 获取栈顶元素

        // 移除超过返回null
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll(2, TimeUnit.SECONDS));
    }

    // 在超过容量时抛出异常
    private static void exception_blockingQueue() {
        // 初始容量为3的队列
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
        queue.add("1");
        queue.add("2");
        queue.add("3");
//        queue.add("3"); // Exception in thread "main" java.lang.IllegalStateException: Queue full

        queue.remove();
        queue.remove();
        queue.remove();
//        queue.remove(); // Exception in thread "main" java.util.NoSuchElementException
    }

}
